package com.gxar.quick.ar.server.base.controller;

import com.alibaba.fastjson.JSON;
import com.gxar.common.entity.Result;
import com.gxar.common.entity.SystemCodeEnum;
import com.gxar.quick.ar.server.base.facade.ShareFacade;
import com.gxar.quick.ar.server.base.model.ResultCodeEnum;
import com.gxar.quick.ar.server.base.model.share.vo.request.UnlimitedQRCodeRequest;
import com.gxar.quick.ar.server.base.model.share.vo.response.UnlimitedQRCodeResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author nice
 * @version 1.0
 * @created 2023/11/25.
 */
@Api(tags = "分享接口")
@RestController
@RequestMapping("/api/share")
@RequiredArgsConstructor
@Slf4j
public class ShareController {

    private final ShareFacade shareFacade;

    @ApiOperation("获取不限制的小程序码")
    @PostMapping("/getUnlimitedQRCode")
    public Result<UnlimitedQRCodeResponse> getUnlimitedQRCode(@RequestBody UnlimitedQRCodeRequest request) {
        UnlimitedQRCodeResponse result = shareFacade.getUnlimitedQRCode(request);
        return Result.success(result);
    }

    @ApiOperation("获取不限制的小程序码返回流")
    @GetMapping(value = "/unlimited-qr-code/{work_id}.{file_type}")
    public void getFile(HttpServletRequest request, HttpServletResponse response, @PathVariable("work_id") String workId, @PathVariable("file_type") String fileType) {
        if (StringUtils.isBlank(workId) || workId.equals("null") || StringUtils.isBlank(fileType) || fileType.equals("null")) {
            try {
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(Result.error(SystemCodeEnum.SPRING_REQUEST_RESOLVER)));
                writer.flush();
                writer.close();
                return;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        response.setContentType("image/jpeg");
        String fileName = workId + "." + fileType;
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        shareFacade.getUnlimitedQRCode(response, workId, "pages/scan/index");
    }

}
